package com.datastructure.test.decodestring;

import java.util.Iterator;
import java.util.Stack;

public class DecodeString {

    public static void main(String[] args) {
        DecodeString decodeString = new DecodeString();
        System.out.println(decodeString.decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
    }

    private String decodeString(String s) {
        int length = s.length();
        if(length==3||!s.contains("[")){
            return s;
        }
        Stack<StringBuilder> tempStack = new Stack<>();
        StringBuilder tempString;
        Stack<StringBuilder> resultStack = new Stack<>();
        StringBuilder resultString;
        int time;
        for (int i = 0; i < length-3; i++) {
            if(Character.isDigit(s.charAt(i))&&s.charAt(i+1)=='['&&Character.isLetter(s.charAt(i+2))){
                time=s.charAt(i);
                tempString = new StringBuilder();
                resultString = new StringBuilder();
                tempString.append(s, i, i+2);
                int j = i+2;
                while (Character.isLetter(s.charAt(j))){
                    tempString.append(s.charAt(j));
                    resultString.append(s.charAt(j));
                    j++;
                }
                tempString.append(']');
                tempStack.add(tempString);
                String temp = resultString.toString();
                StringBuilder result = new StringBuilder();
                for (int k = 0; k < time-48; k++) {
                    result.append(temp);
                }
                resultStack.add(result);
            }
        }
        Iterator<StringBuilder> tempIterator = tempStack.iterator();
        Iterator<StringBuilder> resultIterator = resultStack.iterator();
        while (tempIterator.hasNext()) {
            s=s.replace(tempIterator.next(), resultIterator.next());
        }
        return decodeString(s);
    }

}
